﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.ComponentModel;

namespace SimoBotRewritten
{ 
    public class Statser
    {
        public MySqlCommand cmd;
        public MySqlConnection connect;
        public string ConnectionString;
        public MySqlDataReader Reader;

        List<string> NickList = new List<string>();

        bool LocalDBNickListBuildNeeded = true;

        BackgroundWorker bgwStatser = new BackgroundWorker();

        Parser ParseMachine;

        public Statser(Parser pr)
        {
            bgwStatser.DoWork += new DoWorkEventHandler(bgwStatser_DoWork);
            ParseMachine = pr;

        }
        string output;
        string[] outputArray;
        public void MakeStats(string op, string[] oA)
        {
            output = op;
            outputArray = oA;

            if(!bgwStatser.IsBusy)
            bgwStatser.RunWorkerAsync();
        }

        private void bgwStatser_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bgwStatser = sender as BackgroundWorker;
            MakeMsgCountAndAddToLocalDB(output, outputArray);

        }

        private void bgwStatser_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            
        }

        private void InitializeLocalMySQL()
        {
            ConnectionString = "SERVER=127.0.0.1;" + "DATABASE=simostatsdb;" + "UID=root;" + "PASSWORD=mongobongo;" + "Pooling=true;";
            connect = new MySqlConnection(ConnectionString);
            cmd = connect.CreateCommand();
        }


        private void SetLocalNickListArray()
        {
            LocalDBNickListBuildNeeded = false;
            cmd.CommandText = "SELECT DISTINCT nick FROM simomsg;";
            connect.Open();
            Reader = cmd.ExecuteReader();

            while (Reader.Read())
            {
                for (int i = 0; i < Reader.FieldCount; i++)
                {
                    NickList.Add(Reader.GetValue(i).ToString());
                }
            }




            connect.Close();
            
        }

        private bool IsNewNick(string Nick)
        {
            cmd.CommandText = "SELECT COUNT(*) FROM msgcountstat WHERE nick = '" + Nick + "';";
            connect.Open();
            Reader = cmd.ExecuteReader();
            bool NickIsNew;
            Reader.Read();
            int NumberOfRows = Convert.ToInt32(Reader.GetValue(0).ToString());
            if (NumberOfRows == 0)
            {
                NickIsNew = true;
            }
            else
            {
                NickIsNew = false;
            }

            connect.Close();
            return NickIsNew;
        }

        private void AddAndCreateMsgCountStatLocalDB()
        {

            for (int i = 0; i < NickList.Count; i++)
            {
                bool NickIsNew = IsNewNick(NickList[i].ToString());
                if (NickIsNew)
                {
                    cmd.CommandText = GetNewNickStatCmdText(NickList[i].ToString());
                }
                else
                {
                    cmd.CommandText = GetOldNickCmdText(NickList[i].ToString());      
                }

                connect.Open();
                Reader = cmd.ExecuteReader();
                connect.Close();

            }
        }

        private string GetOldNickCmdText(string Nick)
        {
            string OldNickStatCmdText = "";

            cmd.CommandText = "SELECT COUNT(*) FROM simomsg WHERE nick = '" + Nick + "';";

            connect.Open();
            Reader = cmd.ExecuteReader();
            Reader.Read();
            int msgCount = Convert.ToInt32(Reader.GetValue(0).ToString());

            OldNickStatCmdText = "UPDATE msgCountStat SET msgCount = '" + msgCount + "' WHERE nick = '" + Nick + "';";

            connect.Close();

            return OldNickStatCmdText;
        }

        private string GetNewNickStatCmdText(string Nick)
        {
            string NewNickStatCmdText = "";

                cmd.CommandText = "SELECT COUNT(*) FROM simomsg WHERE nick = '" + Nick + "';";

                connect.Open();
                Reader = cmd.ExecuteReader();
                Reader.Read();

                NewNickStatCmdText = "INSERT INTO msgCountStat VALUES ('" + Nick + "','" + Reader.GetValue(0).ToString() + "');";
                
                connect.Close();

            return NewNickStatCmdText;
        }

        
        private void MakeMsgCountAndAddToLocalDB(string output, string[] outputArray)
        {
            try
            {
                InitializeLocalMySQL();                     //Set the default values

                

                if (LocalDBNickListBuildNeeded == true)
                {
                    SetLocalNickListArray();                // Make a NickList of type list<string> from the local database... 
                    LocalDBNickListBuildNeeded = false;
                }

                AddAndCreateMsgCountStatLocalDB();          //And finally add the newly made statistic to the local database
            }


            catch(Exception mysqlshittii)
            {
                string aids = mysqlshittii.Message;
            }


            /*Should I need to alter the function so that it returns the stat, this one tinkers it to a rather readable form.
             * 
            string[] msgCountStat = new string[NickList.Count];
            for (int i = 0; i < NickList.Count; i++)
            msgCountStat[i] = NickList[i] + '\t' + MsgCount[i].ToString();
            return msgCountStat;
            */

        }


    }
}
